from django.conf import settings
from django.contrib.auth import logout
from django.contrib.auth.models import User
from django.core.servers.basehttp import FileWrapper
from django.http import HttpResponse, Http404, HttpResponseRedirect
from jobboard.forms import *
from jobboard.models import *
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.core.files.base import ContentFile
from django.utils.text import *
import mimetypes
import os
import re


def main_page(request):
	return render_to_response(
		'main_page.html', RequestContext(request)
	)

def logout_page(request):
	logout(request)
	return HttpResponseRedirect('/')

def register_page(request):
	if request.method == 'POST':
		form = RegistrationForm(request.POST)
		if form.is_valid():
			user = User.objects.create_user(
				username=form.cleaned_data['username'],
				password=form.cleaned_data['password1'],
				email=form.cleaned_data['email'],
			)
			user.first_name = form.cleaned_data['first_name']
			user.last_name = form.cleaned_data['last_name']
			user.save()
						
			account = Account(
				user=user,
				address1 = form.cleaned_data['address1'],
				address2 = form.cleaned_data['address2'],
				city = form.cleaned_data['city'],
				state = form.cleaned_data['state'],
				country = form.cleaned_data['country'],
				postalcode = form.cleaned_data['postalcode'],
				
				birthday = form.cleaned_data['birthday'],
				phone = form.cleaned_data['phone'],
				website = form.cleaned_data['website'],				
			)
			
			if (request.FILES.has_key('resume')):
				account.resume = request.FILES['resume']
				account.save()
				save_resume(user)
			else:
				account.save()
			
			return HttpResponseRedirect('/register/success/')
	else:
		form = RegistrationForm()
	variables = RequestContext(request, {
		'form': form
	})
	return render_to_response(
		'registration/register.html',
		variables
	)

def user_settings(request):
	if request.user.is_authenticated():
		return render_to_response(
			'user_settings.html', RequestContext(request)
		)
	return HttpResponseRedirect('/login/')

def user_account(request):
	user = request.user
	if request.method == 'POST' and request.user.is_authenticated():
		form = AccountForm(request.POST)
		if form.is_valid():
			account = user.account
			user.email = form.cleaned_data['email']
			user.first_name = form.cleaned_data['first_name']
			user.last_name = form.cleaned_data['last_name']
			user.save()

			user.account.address1 = form.cleaned_data['address1']
			user.account.address2 = form.cleaned_data['address2']
			user.account.city = form.cleaned_data['city']
			user.account.state = form.cleaned_data['state']
			user.account.country = form.cleaned_data['country']
			user.account.postalcode = form.cleaned_data['postalcode']
			
			user.account.birthday = form.cleaned_data['birthday']
			user.account.phone = form.cleaned_data['phone']
			user.account.website = form.cleaned_data['website']

			user.account.save()
			
			return HttpResponseRedirect('/user/')
	elif not request.user.is_authenticated():
		return HttpResponseRedirect('/login/')
	else:
		user.account = get_or_create_account(user)
		form = AccountForm(initial={
			'first_name': user.first_name,
			'last_name': user.last_name,
			'email': user.email,
			'address1': user.account.address1,
			'address2': user.account.address2,
			'city': user.account.city,
			'state': user.account.state,
			'postalcode': user.account.postalcode,
			'country': user.account.country,
			'birthday': user.account.birthday,
			'phone': user.account.phone,
			'website' : user.account.website,
		})
	variables = RequestContext(request, {
		'user': user,
		'account' : user.account,
		'form': form,
	})
	return render_to_response('user_account.html', variables)

def user_profile(request):
	user =  request.user
	if request.user.is_authenticated():
		return HttpResponseRedirect('/profile/%s' % user.username)
	else:
		return HttpResponseRedirect('/login/')
		
def user_privacy(request):
	user =  request.user
	if request.method == 'POST' and request.user.is_authenticated():
		form = ProfileForm(request.POST)
		if form.is_valid():
			account = user.account
			account.view_email = form.cleaned_data['view_email']
			account.view_phone = form.cleaned_data['view_phone']
			account.view_website = form.cleaned_data['view_website']
			account.view_resume = form.cleaned_data['view_resume']
			account.view_address = form.cleaned_data['view_address']
			account.view_city = form.cleaned_data['view_city']
			account.view_state = form.cleaned_data['view_state']
			account.view_country = form.cleaned_data['view_country']
			account.personal_statement = form.cleaned_data['personal_statement']

			account.save()
			
			return HttpResponseRedirect('/user/')
	elif not request.user.is_authenticated():
		return HttpResponseRedirect('/login/')
	else:
		form = ProfileForm(initial={
			'view_email' : user.account.view_email,
			'view_phone' : user.account.view_phone,
			'view_website' : user.account.view_website,
			'view_resume' : user.account.view_resume,
			'view_address' : user.account.view_address,
			'view_city' : user.account.view_city,
			'view_state' : user.account.view_state,
			'view_country' : user.account.view_country,
			'personal_statement' : user.account.personal_statement

		})
	variables = RequestContext(request, {
		'user': user,
		'account' : user.account,
		'form': form,
	})
	return render_to_response('user_privacy.html', variables)

def user_resume(request):
	user = request.user
	filename = None
	if request.user.is_authenticated():
		if user.account.resume:
			filename = re.search('(\w+\.\w+)$', user.account.resume.name).group(1)	
		if request.method == 'POST':
			account = user.account
			form = ResumeForm(request.POST)
			if (request.FILES.has_key('resume')):
				account.resume = request.FILES['resume']
				account.save()
				save_resume(user)
			else:
				account.save()
			
			return HttpResponseRedirect('/user/resume')
		else:
			form = ResumeForm()
		variables = RequestContext(request, {
			'form': form,
			'filename': filename,
		})
		return render_to_response(
			'user_resume.html',
			variables
		)
	return HttpResponseRedirect('/login/')

def delete_resume(request):
	user = request.user
	if request.user.is_authenticated():
		account = user.account
		path = os.path.join(settings.MEDIA_ROOT, user.account.resume.name)
		account.resume = None
		account.save()
		os.remove(path)
	return HttpResponseRedirect('/user/resume/')

def user_delete(request):
	user = request.user
	if request.user.is_authenticated():
		if user.account:
			account = user.account
			if user.account.resume:
				path = os.path.join(settings.MEDIA_ROOT, user.account.resume.name)
				account.resume = None
				account.save()
				os.remove(path)
			# delete postings, favorite		
			account.delete()
		user.delete()
		logout(request)	
	return HttpResponseRedirect('/')

def get_profile(request, username):
	try:
		user = User.objects.get(username=username)
	except User.DoesNotExist:
		raise Http404(u'Requested user not found.')
	statement = None
	if user.account.personal_statement:
		statement = user.account.personal_statement
		statement = wrap(statement, 60)
	variables = RequestContext(request, {
		'person': user,
		'statement' : statement,
	})
	return render_to_response(
		'profile.html',
		variables
	)
		
def get_resume(request, username):
	try:
		user = User.objects.get(username=username)
	except User.DoesNotExist:
		raise Http404(u'Requested user not found.')
	path = os.path.join(settings.MEDIA_ROOT, user.account.resume.name)
	name = re.search('(\w+\.\w+)$', user.account.resume.name)
	wrapper = FileWrapper(open(path))
	content_type = mimetypes.guess_type(path)[0]
	if content_type == None:
		content_type = 'application/force-download'
	response = HttpResponse(wrapper,content_type=content_type)
	response['Content-Disposition'] = 'attachment; filename=%s' % name.group(1)
	response['Content-Length'] = response['Content-Length'] = os.path.getsize(path)
	return response
	
def create_job(request):
	user = request.user
	if request.user.is_authenticated():
		if request.method == 'POST':
			form = JobForm(request.POST)
			if form.is_valid():
				_job = Job(
					owner = user,
					title = form.cleaned_data['title'],
					company = form.cleaned_data['company'],
					pay = form.cleaned_data['pay'],
					description = form.cleaned_data['description'],
				)
				_job.save()
				for filter in Filter.objects.all():
					if form.cleaned_data[filter.description]:
						quality = JobQualities(
							job = _job,
							filter = filter,
						)
						quality.save()
				return HttpResponseRedirect('/user')
		else:
			form = JobForm()
		variables = RequestContext(request, {
			'form': form,
		})
		return render_to_response(
			'create_job.html',
			variables
		)
	else:
		return HttpResponseRedirect('/login')


def edit_job(request, jobid):
	user = request.user
	if request.user.is_authenticated():
		job = Job.objects.get(id = jobid)
		if request.method == 'POST':
			form = JobForm(request.POST)
			if form.is_valid() and (user == job.owner):
				job.title = form.cleaned_data['title']
				job.company = form.cleaned_data['company']
				job.pay = form.cleaned_data['pay']
				job.description = form.cleaned_data['description']
				job.save()
				
				for filter in Filter.objects.all():	#Look at all 4 known filters, one at a time
					new_setting = form.cleaned_data[filter.description]	# Look to see if this filter was just turned on
					prev_setting = JobQualities.objects.filter(job=job, filter=filter) # Check to see if it was previously turned on
					if len(prev_setting) > 0: #The filter was turned on in the job
						if not new_setting: #The filter was on, now it's switched off
							previous = prev_setting[0] #Get the old filter-job pair (jobquality) and delete it
							previous.delete()
						else: # The filter was on, this was not changed
							pass	# Nothing to do
					else: #The filter was turned off in the job
						if new_setting: #The filter was off, now it's on
							new_quality = JobQualities( # Make a new quality (filter-job par) and save it
								job = job,
								filter = filter,
							)
							new_quality.save()
						else: #The filter was off, no change
							pass
				return HttpResponseRedirect('/user/manage_jobs')
		else:			
			filters = {}
			for filter in Filter.objects.all():
				prev_setting = JobQualities.objects.filter(job=job, filter=filter)
				if len(prev_setting) > 0:
					filters[filter.description] = True
				else:
					filters[filter.description] = False
			form = JobForm(initial={
				'title': job.title,
				'company': job.company,
				'pay': job.pay,
				'description': job.description,
				'FullTime' : filters['FullTime'],
				'PartTime' : filters['PartTime'],
				'Salary' : filters['Salary'],
				'Hourly' : filters['Hourly'],	
			})
		variables = RequestContext(request, {
			'form': form,
		})
		return render_to_response('edit_job.html', variables)
	else:
		return HttpResponseRedirect('/login/')
	


def manage_jobs(request):
	user = request.user
	if request.user.is_authenticated():
		myjobs = Job.objects.filter(owner = user)
	list = []
	for job in myjobs:
		list.append(job)
	list.reverse()
	variables = RequestContext(request, {
		'list' : list,
	})
	return render_to_response(
		'manage_jobs.html',
		variables
	)

def delete_job(request, jobid):
	user = request.user
	if request.user.is_authenticated():
		job = Job.objects.get(id = jobid)
		if job.owner == user:
			job.delete()
			return HttpResponseRedirect('/user/manage_jobs/')
	return HttpResponseRedirect('/')

def get_personnel(request):
	personnel = Account.objects.order_by('last_modified')
	users = []
	for person in personnel:
		if not person.user.is_superuser:
			users.append(person.user)
	users.reverse()
	variables = RequestContext(request, {
		'list' : users,
	})
	return render_to_response(
		'personnel.html',
		variables
	)

def get_jobs(request):
	jobs = Job.objects.order_by('last_modified')
	list = []
	for job in jobs:
		list.append(job)
	finishers = []
	finishers.extend(list)
	if request.method == 'POST':
		form = FilterForm(request.POST)
		if form.is_valid():
			settings = []
			filters = Filter.objects.all()
			for filter in filters:
				if form.cleaned_data[filter.description]:
					settings.append(filter)
			for job in list:
				for filter in settings:
					result = JobQualities.objects.filter(job=job, filter=filter) 
					if len(result) == 0 and (finishers.count(job) > 0):
						finishers.remove(job)
	else:
		form = FilterForm()
	list.reverse()
	variables = RequestContext(request, {
		'list' : finishers,
		'form' : form,
	})
	return render_to_response(
		'jobs.html',
		variables
	)

def favorite_jobs(request):
	user = request.user
	if request.user.is_authenticated():
		joblist = FavoriteJob.objects.filter(account=user)
		list = []
		for favorite in joblist:
			list.append(favorite.job)
		variables = RequestContext(request, {
			'list' : list,
		})
		return render_to_response(
			'favorite_jobs.html',
			variables
		)
	return HttpResponseRedirect('/login/')

def add_fav_job(request, jobid):
	user = request.user
	if request.user.is_authenticated():
		fav_list = FavoriteJob.objects.filter(job = Job.objects.get(id=jobid), account=user)
		if len(fav_list) < 1:
			fav = FavoriteJob(
				job = Job.objects.get(id=jobid),
				account = user,
			)
			fav.save()
	return HttpResponseRedirect('/jobs/')

def remove_fav_job(request, jobid):
	user = request.user
	if request.user.is_authenticated():
		fav_list = FavoriteJob.objects.filter(job = Job.objects.get(id=jobid), account=user)
		for fav in fav_list:
			fav.delete()
	return HttpResponseRedirect('/jobs/favorite/')

def favorite_people(request):
	user = request.user
	if request.user.is_authenticated():
		rlist = FavoriteRecruit.objects.filter(employer=user)
		list = []
		for favorite in rlist:
			list.append(favorite.job_recruit)
		variables = RequestContext(request, {
			'list' : list,
		})
		return render_to_response(
			'favorite_people.html',
			variables
		)
	return HttpResponseRedirect('/login/')

def add_fav_people(request, _username):
	user = request.user
	if request.user.is_authenticated():
		fav_list = FavoriteRecruit.objects.filter(job_recruit = User.objects.get(username=_username), employer=user)
		if len(fav_list) < 1:
			fav = FavoriteRecruit(
				job_recruit = User.objects.get(username=_username),
				employer = user,
			)
			fav.save()
	return HttpResponseRedirect('/personnel/')

def remove_fav_people(request, _username):
	user = request.user
	if request.user.is_authenticated():
		fav_list = FavoriteRecruit.objects.filter(job_recruit = User.objects.get(username=_username), employer=user)
		for fav in fav_list:
			fav.delete()
	return HttpResponseRedirect('/user/favorite/')

def save_resume(user):
	old_resume = user.account.resume.name
	ext = re.search('(\.\w+)$', old_resume)
	path = settings.MEDIA_ROOT + "resumes/" + user.username + ext.group(1)
	content = ContentFile(user.account.resume.read())
	user.account.resume.save(path, content)
	user.save()
	oldpath = settings.MEDIA_ROOT + old_resume
	os.remove(oldpath)
